﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SmartParkingServer.IService;
using SmartParkingServer.Models;
using SmartParkingServer.Service;
using System;
using System.Linq;

namespace SmartParkingServer.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        IUserService _userService;
        public LoginController(IUserService userService)
        {
            _userService = userService;
        }

        /// <summary>
        /// FromFrom http://localhost:5000/login?username=admin&password=admin
        /// </summary>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Post([FromForm] string username, [FromForm] string password)
        {
            //用户名 和 密码
            //返回验证状态
            //数据库对比

            //var users = _userService.Query<UserModel>(u => u.UserName == username && u.Password == password).ToList();

            Result<UserModel> result = new Result<UserModel>();
            try
            {
                if (_userService.Login(username, password, out UserModel userModel))
                {
                    // 暂时返回这个状态     后续需要用户相关信息返回（权限菜单）
                    result.Data = userModel;
                    result.State = 200;
                }
                else
                {
                    result.State = 500;
                    result.ExceptionMessage = "用户名或密码错误";
                }
            }
            catch (Exception ex)
            {
                result.State = 501;
                result.ExceptionMessage = ex.Message;
            }
            return Ok(result);
        }

        /// <summary>
        /// 如果认证不通过   返回401状态
        /// </summary>
        /// <returns></returns>
        [Authorize]
        [HttpGet]
        public IActionResult Get()
        {
            return Ok("测试成功");
        }
    }
}
